#include <stdio.h>
#include <string.h>
#include <mysql.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <aio.h>

#define MAX_BUF 4096
#define MAX_NAME 128
static void aio_out(sigval_t sigval);

my_bool mfset_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void mfset_deinit(UDF_INIT *initid);
long long  mfset(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error);

my_bool mfset_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
	if(args->arg_count != 2 || args->lengths[0] == 0 ||args->lengths[1] == 0 )
	{
		strcpy(message,"Please give 2 argements!");
		return 1;
	}
	int i;
	for(i=0;i<args->arg_count;i++)
	{
		args->arg_type[i]=STRING_RESULT;
	}
	return 0;
}

void mfset_deinit(UDF_INIT *initid)
{
}

long long  mfset(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
	char *fn=args->args[0];
	int fnl=args->lengths[0];
	if(fnl > MAX_NAME-1)
	{
		return -1;
	}
	char name[MAX_NAME]={0};
	strncpy(name,fn,fnl);

	char *str=args->args[1];
	int strl=args->lengths[1];
	if(strl > MAX_BUF-1)
	{
		strl=MAX_BUF-1;
	}
	char *buf=calloc(1,MAX_BUF);
	strncpy(buf,str,strl);
	int wlen=strl + 64 - (strl % 64);
	/*
	static FILE *fp=NULL;
	if(!fp)
		fp=fopen(name,"a");
	if(!fp)
	{
		return -2;
	}
	size_t num=fwrite(buf,wlen,1,fp);	
	fclose(fp);
	*/

	static int fd=0;
	if(!fd)
		fd=open(name,O_RDWR|O_APPEND);
	if(!fd)
		return -2;
	ssize_t num=write(fd,buf,wlen);
	return num;
	/*
	struct aiocb *acb=calloc(1,sizeof(struct aiocb));
	memset(acb,0,sizeof(struct aiocb));
	acb->aio_fildes=fd;
	acb->aio_buf=buf;
	acb->aio_nbytes=wlen;
	acb->aio_offset=0;
	acb->aio_sigevent.sigev_notify=SIGEV_THREAD;
	acb->aio_sigevent._sigev_un._sigev_thread._function=aio_out;
	acb->aio_sigevent._sigev_un._sigev_thread._attribute=NULL;
	acb->aio_sigevent.sigev_value.sival_ptr=acb;
	return aio_write(acb);
	*/
}

static void aio_out(sigval_t sigval)
{
	struct aiocb *acb=(struct aiocb *)sigval.sival_ptr;
	if(aio_error(acb) == 0)
		aio_return(acb);
	free((void *)acb->aio_buf);
	free(acb);
}
